package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.RedisData;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>

 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 解决缓存的各种问题
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
      //  解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class
                , this::getById, CACHE_SHOP_TTL, TimeUnit.SECONDS);


//        //利用互斥锁解决解决缓存击穿
//        Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

         //逻辑过期时间解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, CACHE_SHOP_TTL, TimeUnit.SECONDS);

        if(shop == null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);

    }


    /**
     * 从缓存中获取店铺数据,判断缓存是否命中
     *
     * @param key
     * @return
     */
    private Result getShopFromCache(String key) {

        String result = stringRedisTemplate.opsForValue().get(key);
        //1.判断缓存是否命中
        if (StrUtil.isNotBlank(result)) {
            //缓存数据有值，说明缓存命中了，直接返回
            Shop shop = JSONUtil.toBean(result, Shop.class);
            return Result.ok(shop);
        }
        //2.如果等于"",说明缓存也命中了(为了解决缓存穿透缓存的"",返回错误信息即可)
        if (result != null) {
            return Result.fail("店铺不存在");
        }
        //3.缓存未命中(缓存的对象即没有值，也不是空字符串)
        return null;
    }


    @Transactional
    @Override
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        boolean d = updateById(shop);
        if(!d){
            //保证缓存和数据库的一致性,抛出异常进行事务回滚
            throw new RuntimeException("数据库更新失败！");
        }

        String key = CACHE_SHOP_KEY + id;
        //2.删除缓存，保证下一次查到最新数据
        Boolean c = stringRedisTemplate.delete(key);
        if(!c){
            //保证缓存和数据库的一致性,抛出异常进行事务回滚
            throw new RuntimeException("删除缓存失败！");
        }

        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
     //1.判断是否需要根据坐标来查
        if(x == null || y == null){
            //不需要则按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3.查询redis,按照距离排序，分页。结果为shopId,distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoRadiusCommandArgs
                        .newGeoRadiusArgs().includeDistance().limit(end));
        //4.解释出id
        if(results == null ){
            return Result.ok(Collections.emptyList());
        }

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();

        if(list.size()<=from){
            //没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //4.1截取from-end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach( result -> {
             //4.2获取店铺id
             String shopIdStr = result.getContent().getName();
             ids.add(Long.valueOf(shopIdStr));
             //4.3获取距离
             Distance distance = result.getDistance();
             distanceMap.put(shopIdStr, distance);
                }
        );
      //5.根据id查询店铺
        String idStr = StrUtil.join(",",ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Shop shop : shops) {

            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //6.返回
        return Result.ok(shops);
    }
}
